{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "def get_current_temperature(location: str, unit: str = \"celsius\"):\n",
    "    \"\"\"Get current temperature at a location.\n",
    "\n",
    "    Args:\n",
    "        location: The location to get the temperature for, in the format \"City, State, Country\".\n",
    "        unit: The unit to return the temperature in. Defaults to \"celsius\". (choices: [\"celsius\", \"fahrenheit\"])\n",
    "\n",
    "    Returns:\n",
    "        the temperature, the location, and the unit in a dict\n",
    "    \"\"\"\n",
    "    return {\n",
    "        \"temperature\": 26.1,\n",
    "        \"location\": location,\n",
    "        \"unit\": unit,\n",
    "    }\n",
    "\n",
    "\n",
    "def get_temperature_date(location: str, date: str, unit: str = \"celsius\"):\n",
    "    \"\"\"Get temperature at a location and date.\n",
    "\n",
    "    Args:\n",
    "        location: The location to get the temperature for, in the format \"City, State, Country\".\n",
    "        date: The date to get the temperature for, in the format \"Year-Month-Day\".\n",
    "        unit: The unit to return the temperature in. Defaults to \"celsius\". (choices: [\"celsius\", \"fahrenheit\"])\n",
    "\n",
    "    Returns:\n",
    "        the temperature, the location, the date and the unit in a dict\n",
    "    \"\"\"\n",
    "    return {\n",
    "        \"temperature\": 25.9,\n",
    "        \"location\": location,\n",
    "        \"date\": date,\n",
    "        \"unit\": unit,\n",
    "    }\n",
    "\n",
    "def get_function_by_name(name):\n",
    "    if name == \"get_current_temperature\":\n",
    "        return get_current_temperature\n",
    "    if name == \"get_temperature_date\":\n",
    "        return get_temperature_date\n",
    "\n",
    "TOOLS = [\n",
    "    {\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\n",
    "            \"name\": \"get_current_temperature\",\n",
    "            \"description\": \"Get current temperature at a location.\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"location\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": 'The location to get the temperature for, in the format \"City, State, Country\".',\n",
    "                    },\n",
    "                    \"unit\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"enum\": [\"celsius\", \"fahrenheit\"],\n",
    "                        \"description\": 'The unit to return the temperature in. Defaults to \"celsius\".',\n",
    "                    },\n",
    "                },\n",
    "                \"required\": [\"location\"],\n",
    "            },\n",
    "        },\n",
    "    },\n",
    "    {\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\n",
    "            \"name\": \"get_temperature_date\",\n",
    "            \"description\": \"Get temperature at a location and date.\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"location\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": 'The location to get the temperature for, in the format \"City, State, Country\".',\n",
    "                    },\n",
    "                    \"date\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": 'The date to get the temperature for, in the format \"Year-Month-Day\".',\n",
    "                    },\n",
    "                    \"unit\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"enum\": [\"celsius\", \"fahrenheit\"],\n",
    "                        \"description\": 'The unit to return the temperature in. Defaults to \"celsius\".',\n",
    "                    },\n",
    "                },\n",
    "                \"required\": [\"location\", \"date\"],\n",
    "            },\n",
    "        },\n",
    "    },\n",
    "]\n",
    "MESSAGES = [\n",
    "    {\"role\": \"system\", \"content\": \"You are Qwen, created by Alibaba Cloud. You are a helpful assistant.\\n\\nCurrent Date: 2024-09-30\"},\n",
    "    {\"role\": \"user\",  \"content\": \"What's the temperature in San Francisco now? How about tomorrow?\"},\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "函数调用计划：\n",
      "[{'role': 'system', 'content': 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.\\n\\nCurrent Date: 2024-09-30'}, {'role': 'user', 'content': \"What's the temperature in San Francisco now? How about tomorrow?\"}, {'role': 'assistant', 'content': '', 'function_call': {'name': 'get_current_temperature', 'arguments': '{\"location\": \"San Francisco, California, USA\"}'}}, {'role': 'assistant', 'content': '', 'function_call': {'name': 'get_temperature_date', 'arguments': '{\"location\": \"San Francisco, California, USA\", \"date\": \"2024-10-01\"}'}}]\n",
      "函数调用结果：\n",
      "[{'role': 'system', 'content': 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.\\n\\nCurrent Date: 2024-09-30'}, {'role': 'user', 'content': \"What's the temperature in San Francisco now? How about tomorrow?\"}, {'role': 'assistant', 'content': '', 'function_call': {'name': 'get_current_temperature', 'arguments': '{\"location\": \"San Francisco, California, USA\"}'}}, {'role': 'assistant', 'content': '', 'function_call': {'name': 'get_temperature_date', 'arguments': '{\"location\": \"San Francisco, California, USA\", \"date\": \"2024-10-01\"}'}}, {'role': 'function', 'name': 'get_current_temperature', 'content': '{\"temperature\": 26.1, \"location\": \"San Francisco, California, USA\", \"unit\": \"celsius\"}'}, {'role': 'function', 'name': 'get_temperature_date', 'content': '{\"temperature\": 25.9, \"location\": \"San Francisco, California, USA\", \"date\": \"2024-10-01\", \"unit\": \"celsius\"}'}]\n",
      "函数调用最终响应：\n",
      "[{'role': 'assistant', 'content': 'Currently, the temperature in San Francisco is 26.1°C. For tomorrow, October 1st, the expected temperature is 25.9°C.'}]\n"
     ]
    }
   ],
   "source": [
    "from qwen_agent.llm import get_chat_model\n",
    "\n",
    "llm = get_chat_model({\n",
    "    \"model\": \"qwen2.5:14b\",\n",
    "    \"model_server\": \"http://192.168.20.43:11434/v1\",\n",
    "    \"api_key\": \"EMPTY\",\n",
    "})\n",
    "messages = MESSAGES[:]\n",
    "functions = [tool[\"function\"] for tool in TOOLS]\n",
    "\n",
    "# 让llm生成函数调用\n",
    "for responses in llm.chat(\n",
    "    messages=messages,\n",
    "    functions=functions,\n",
    "    extra_generate_cfg=dict(parallel_function_calls=True),\n",
    "):\n",
    "    pass\n",
    "messages.extend(responses)\n",
    "print(\"函数调用计划：\")\n",
    "print(messages)\n",
    "\n",
    "# 检查和执行函数调用\n",
    "for message in responses:\n",
    "    if fn_call := message.get(\"function_call\", None):\n",
    "        fn_name: str = fn_call['name']\n",
    "        fn_args: dict = json.loads(fn_call[\"arguments\"])\n",
    "\n",
    "        fn_res: str = json.dumps(get_function_by_name(fn_name)(**fn_args))\n",
    "\n",
    "        messages.append({\n",
    "            \"role\": \"function\",\n",
    "            \"name\": fn_name,\n",
    "            \"content\": fn_res,\n",
    "        })\n",
    "print(\"函数调用结果：\")\n",
    "print(messages)\n",
    "\n",
    "# 最终响应\n",
    "for responses in llm.chat(messages=messages, functions=functions):\n",
    "    pass\n",
    "messages.extend(responses)\n",
    "print(\"函数调用最终响应：\")\n",
    "#print(messages)\n",
    "print(responses)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
